//
//  UserCompnayVC.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/9/1.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class UserCompnayVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate, RGFadeDelegate, UserCompanyTheMainDelegate, UserCompanyCell2Delegate, BriefTableViewCellDelegate, MTImagePickerControllerDelegate, ActionSheetCustomPickerDelegate, UserCompanyIDCellDelegate{
    
    private var dataSource = [MTImagePickerModel]()//照片的数据源
    
    var actionSheet: UIActionSheet? = nil
    var imagePicker: UIImagePickerController? = nil
    var IMG: UIImage!
    var msg: regiestInfo?
    var footerView = UserCompanyFooter.create()
    var modityDic: NSDictionary!
    var rgFadeView: RGFadeView?
    var userCompanyTheMain: UserCompanyTheMain?
    @IBOutlet weak var tableView: UITableView!
    var type : String = ""
    var index: Int?
    var brief: String!
    var index1: NSInteger = 0 // 省下标
    var index2: NSInteger = 0 // 市下标
    var index3: NSInteger = 0 // 区下标
    
    var provinceArr: NSArray! //省
    var countryArr: NSArray! // 市
    var districtArr: NSArray! // 区
    var addressArr: NSArray! // 解析出来的最外层的数组
    
    //第三方绑定用的
    var json: String?
    var number: String?
    var bingdingtype: String?
    
    var comeFrom: String!
    
    var model: userPersonCompany?{
        didSet{
            self.tableView.reloadData()
        }
    }
    var imgArr: [UIImage] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.title = "企业信息"
        
        footerView.quitBtn .addTarget(self, action: #selector(UserCompnayVC.signOut), forControlEvents: UIControlEvents.TouchUpInside )
        
       
        self.tableView.tableFooterView = footerView
        if (actionSheet == nil) {
            self.actionSheet = UIActionSheet(title: "选择照片",delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "拍照", "从手机相册选择")
        }
        
        let cellNib = UINib(nibName: "UserCompanyInfoCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "UserCompanyInfoCell")
        
        let cellNib1 = UINib(nibName: "UserCompanyCell2", bundle: nil)
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "UserCompanyCell2")
        
        let cellNib2 = UINib(nibName: "UserCompanyIDCell", bundle: nil)
        self.tableView.registerNib(cellNib2, forCellReuseIdentifier: "UserCompanyIDCell")
        
        let cellNib3 = UINib(nibName: "BriefTableViewCell", bundle: nil)
        self.tableView.registerNib(cellNib3, forCellReuseIdentifier: "BriefTableViewCell")
        
        self.calculateFirstData()
        
        self.getUserCompanyInfo()
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = NAVIGATIONBAR_RED_COLOR
        
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    
    func calculateFirstData(){
        
        loadFirstData()
        let cityNameArr = NSMutableArray()
        
        print(addressArr.count)
        for cityName in (addressArr[index1].allValues.first) as! NSArray {
            
            let name1 = (cityName as! NSDictionary).allKeys.first
            cityNameArr.addObject(name1!)
        }
        // 组装对应省下面的市
        countryArr = cityNameArr
        
        districtArr = addressArr[index1].allObjects[0][index2].allValues[0] as! NSArray
        
    }
    func loadFirstData(){
        
        let path = NSBundle.mainBundle().pathForResource("address", ofType: "json")
        print(path)
        
        let data = NSData.init(contentsOfFile: path!)
        
        guard let myArr = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) else {
            
            return
        }
        
        addressArr = myArr as! NSArray
        
        let firstName = NSMutableArray()
        for dict in addressArr {
            
            let name = (dict as! NSDictionary).allKeys.first
            firstName.addObject(name!)
        }
        provinceArr = firstName
        
        
    }
    //MARK: UIPickerViewDataSource Implementation
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int{
        switch (component)
        {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        
        default:break;
        }
        return 0;
    }
    
    func pickerView(pickerView: UIPickerView,
                    titleForRow row: Int,
                                forComponent component: Int) -> String?{
        
        switch (component)
        {
        case 0: return self.provinceArr[row] as? String
        case 1: return self.countryArr[row] as? String
       
        default:break;
        }
        return nil;
    }
    func pickerView(pickerView: UIPickerView,
                    viewForRow row: Int,
                               forComponent component: Int,
                                            reusing view: UIView?) -> UIView{
        
        
        let label: UILabel! = UILabel()
        label!.font = UIFont.systemFontOfSize(14)
        
        var title = ""
        switch component {
        case 0:
            title = self.provinceArr[row] as! String
        case 1:
            title = self.countryArr[row] as! String
        
        default:
            break
        }
        
        label!.textAlignment = NSTextAlignment.Center
        label!.text = title
        return label!
        
    }
    func pickerView(pickerView: UIPickerView,
                    didSelectRow row: Int,
                                 inComponent component: Int){
        switch component {
        case 0:
            self.index1 = row
            self.index2 = 0
           
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            self.calculateFirstData()
            pickerView.reloadComponent(1)
           
            pickerView.selectRow(0, inComponent: 1, animated: true)
           
            
        case 1:
            self.index2 = row
           
        default:
            break
        }
        
    }
    //MARK:点击完成的按钮时执行
    func actionSheetPickerDidSucceed(actionSheetPicker: AbstractActionSheetPicker!, origin: AnyObject!) {
        var detailAddress = String()
        if self.index1 < self.provinceArr.count {
            let firstAddress = self.provinceArr[self.index1]
            detailAddress += firstAddress as! String
        }
        if self.index2 < self.countryArr.count {
            let secondAddress = self.countryArr[self.index2]
            detailAddress += secondAddress as! String
        }
        
        // 此界面显示
        print(detailAddress)
        self.modityDic = ["unitarea": detailAddress]
        self.modifyUserInfo()
       
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        if self.model == nil{
            return 0
        }else{
            return 3
        }
       
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.model == nil{
            return 0
        }else{
            if section == 0{
                return 8
            }else if section == 1{
                return 3
            }else{
                return 4
            }
        }
        
        
    }
    func tableView(tableView: UITableView,heightForHeaderInSection section: Int) -> CGFloat{
        
        if section == 1{
            return 40
        }else if section == 2{
            return 40
        }else{
            return 0
        }
    
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1{
            let sectionView = NSBundle.mainBundle().loadNibNamed("UserSectionView", owner: nil, options: nil).last as? UserSectionView
            sectionView?.lvl.text = "认证信息"
            return sectionView
        }else{
            let sectionView = NSBundle.mainBundle().loadNibNamed("UserSectionView", owner: nil, options: nil).last as? UserSectionView
             sectionView?.lvl.text = "帐号绑定"
            return sectionView

        }
    
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0{
            if indexPath.row == 0{
                return 100
            }else{
                return 50
            }
        }else if indexPath.section == 1{
            if indexPath.row == 0{
                if self.model?.unitlicense?.count == 0 || self.model?.unitlicense?.count == nil{
                    return 150
                }else{
                    if (self.model?.unitlicense?.count)! % 3 > 0{
                        return CGFloat((((self.model?.unitlicense?.count)! / 3) + 1) * 90 + 50)
                    }else{
                         return CGFloat(((self.model?.unitlicense?.count)! / 3) * 90 + 50)
                    }
                   
                }
                
                
            }else if indexPath.row == 1{
                if self.model?.unitstyle?.count == 0 || self.model?.unitstyle?.count == nil{
                    return 150
                }else{
                    if (self.model?.unitstyle?.count)! % 3 > 0{
                        return CGFloat((((self.model?.unitstyle?.count)! / 3) + 1) * 90 + 50)
                    }else{
                        return CGFloat(((self.model?.unitstyle?.count)! / 3) * 90 + 50)
                    }

                }
            }else{
                return 100
            }
        }else{
            return 50
        }
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.section == 0{
        
        let cell = tableView.dequeueReusableCellWithIdentifier("UserCompanyInfoCell", forIndexPath: indexPath) as! UserCompanyInfoCell
        
        if  indexPath.row == 0{
            cell.valueLbl.hidden = true
            cell.naemLbl.text = "头像"
            cell.noChangeLbl.hidden = true
            cell.iv.sd_setImageWithURL(NSURL(string: model!.timg), placeholderImage: UIImage(named: "placeholder"))
            cell.iv.layer.masksToBounds = true
            cell.iv.layer.cornerRadius = 40
        }else if indexPath.row == 1{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unitname
            cell.naemLbl.text = "企业名称"
            cell.iv.hidden = true
        }else if indexPath.row == 2{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.signature
            cell.naemLbl.text = "签名"
            cell.iv.hidden = true
            cell.noChangeLbl.hidden = true
        }else if indexPath.row == 3{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unittype
            cell.naemLbl.text = "类型"
            cell.iv.hidden = true
        }else if indexPath.row == 4{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unitarea
            cell.naemLbl.text = "位置区域"
            cell.iv.hidden = true
            cell.noChangeLbl.hidden = true
        }else if indexPath.row == 5{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unitaddress
            cell.naemLbl.text = "详细地址"
            cell.iv.hidden = true
            cell.noChangeLbl.hidden = true
        }else if indexPath.row == 6{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unitscale
            cell.naemLbl.text = "企业规格"
            cell.iv.hidden = true
            cell.noChangeLbl.hidden = true
        }else{
            cell.valueLbl.hidden = false
            cell.valueLbl.text = self.model?.unitmain
            cell.naemLbl.text = "主营"
            cell.iv.hidden = true
            cell.noChangeLbl.hidden = true
        }
        return cell
    }else if indexPath.section == 1{
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("UserCompanyCell2", forIndexPath: indexPath) as! UserCompanyCell2
          
           
            cell.delegate = self
            cell.type = "1"
            cell.setCellContentWithCellInfo(self.model?.unitlicense, name: "营业执照:", explain:"核准后的正规企业将开放更多资源,并获得更多推荐机会")
            return cell
        }else if indexPath.row == 1{
            let cell = tableView.dequeueReusableCellWithIdentifier("UserCompanyCell2", forIndexPath: indexPath) as! UserCompanyCell2
            cell.delegate = self
            cell.type = "2"
            cell.setCellContentWithCellInfo(self.model?.unitstyle, name: "企业风采:", explain: "企业面貌和工作环境(有助于提高招聘人才的几率")
            return cell
        }else{
            let cell = tableView.dequeueReusableCellWithIdentifier("BriefTableViewCell", forIndexPath: indexPath) as! BriefTableViewCell
            cell.delegate = self
            if self.model?.introduction == ""{
                cell.textViewPlace.alpha = 1
            }else{
                 cell.textView.text = self.model!.introduction
                cell.textViewPlace.alpha = 0
            }
            
            return cell
        }
       
    }else{
         let cell = tableView.dequeueReusableCellWithIdentifier("UserCompanyIDCell", forIndexPath: indexPath) as! UserCompanyIDCell
        cell.delegate = self
        if indexPath.row == 0{
            cell.name.text = "手机"
            cell.switchState.tag = indexPath.row
            cell.nickName.text = self.model?.phone
            cell.switchState.hidden = true

        }else if indexPath.row == 1{
            cell.nickName.text = self.model?.weixinname
            cell.switchState.tag = indexPath.row
            if self.model?.weixinname.characters.count > 0{
                cell.switchState.on = true
            }else{
                cell.switchState.on = false
            }
            cell.name.text = "微信"
        }else if indexPath.row == 2{
            cell.nickName.text = self.model?.qqname
            cell.switchState.tag = indexPath.row
            if self.model?.qqname.characters.count > 0{
                cell.switchState.on = true
            }else{
                cell.switchState.on = false
            }
             cell.name.text = "腾讯QQ"
        }else{
            cell.nickName.text = self.model?.sinaname
            cell.switchState.tag = indexPath.row
            if self.model?.sinaname.characters.count > 0{
                cell.switchState.on = true
            }else{
                cell.switchState.on = false
            }
             cell.name.text = "新浪微博"
        }
        
        return cell
      }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        index = indexPath.row
        if indexPath.section == 0{
            if indexPath.row == 0{
                self.actionSheet!.showInView(self.view!)
            }else if indexPath.row == 2 || indexPath.row == 5{
                if (rgFadeView == nil) {
                    rgFadeView = RGFadeView.init(frame: kScreen_frame)
                    rgFadeView?.docid = "1"
                    rgFadeView?.delegate = self
                    self.view.addSubview(rgFadeView!)
                }
                
                rgFadeView?.msgTextView.becomeFirstResponder()
            }else if indexPath.row == 4{
                
                 ActionSheetCustomPicker.showPickerWithTitle("位置区域", delegate: self, showCancelButton: true, origin: self.view, initialSelections: [index1, index2])
                
            }else if indexPath.row == 6{
                ActionSheetMultipleStringPicker.showPickerWithTitle("企业规格", rows:[["1-5人", "5-10人", "10-20人", "20-50人", "50-100人" ,"100人以上"]],initialSelection: [1,1], doneBlock: {
                    picker, values, indexes in
                    let obj = (indexes as! NSArray)[0] as! String
                    self.modityDic = ["unitscale": obj]
                    self.modifyUserInfo()
                    return
                    }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
                
            }else if indexPath.row == 7{
           
                userCompanyTheMain = UserCompanyTheMain.init(frame: kScreen_frame)
                userCompanyTheMain?.delegate = self
                self.view.addSubview(userCompanyTheMain!)
          }
        }else if indexPath.section == 1{
            if indexPath.row == 2 {
                self.index = 50
                if (rgFadeView == nil) {
                    rgFadeView = RGFadeView.init(frame: kScreen_frame)
                    rgFadeView?.docid = "1"
                    rgFadeView?.delegate = self
                    self.view.addSubview(rgFadeView!)
                }
                
                rgFadeView?.msgTextView.becomeFirstResponder()
                
            }

        }
        
        
    }
    //MARK:UserCompanyIDCellDelegate
    func choseSwitch(switchState: UISwitch){
        switch switchState.tag {
        case 0:
            break;
        case 1:
            if switchState.on{
               self.wechat()
            }else{
                self.bingdingtype = "weixin"
                self.tiedThirdPartyAccount()
            }
        case 2:
            if switchState.on{
                self.tencent()
            }else{
                 self.bingdingtype = "qq"
                self.tiedThirdPartyAccount()
            }
            
        case 3:
            if switchState.on{
                self.sina()
            }else{
                self.bingdingtype = "sina"
                self.tiedThirdPartyAccount()
            }
            
        default:
            break
        }
    }
    //MARK:UserCompanyCell2Delegate
    func collectionLicenceSelected(){
        DetailPictureView.showLiencePictrue((self.model?.unitlicense)!, index: Int((self.model?.unitlicense?.count)! - 1))
    }
    func collectionStyleSelected(){
        DetailPictureView.showLiencePictrue((self.model?.unitstyle)!, index: Int((self.model?.unitstyle?.count)! - 1))
    }
    
    func photoBtnSelected(type: String){
        self.type = type
        self.btnPickTouch()
    }
    func btnPickTouch() {
    
        var mediaTypes = [MTImagePickerMediaType]()
        let source = MTImagePickerSource.Photos
        mediaTypes.append(MTImagePickerMediaType.Photo)
        let vc = MTImagePickerController.instance
        vc.mediaTypes = mediaTypes
        vc.source = source
        vc.delegate = self
        vc.maxCount = 6
        let nc = UINavigationController(rootViewController: vc)
        self.presentViewController(nc, animated: true, completion: nil)
            
    }
    func getUserInfo(){
        self.getUserCompanyInfo()
    }
    //选取照片相关
    @available(iOS 8.0, *)
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithPhotosModels models: [MTImagePickerPhotosModel]) {
        self.dataSource = models
       
        for index in 0...self.dataSource.count - 1{
            imgArr.append(self.dataSource[index].getThumbImage()!)
        }
        DataTool.upLoadLienceAndStylePhotos(self.imgArr, type: self.type, completionHandler:{ (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
            self.dataSource.removeAll()
            self.imgArr.removeAll()
            self.getUserCompanyInfo()
        })
     
    }
    
    func imagePickerController(picker: MTImagePickerController, didFinishPickingWithAssetsModels models: [MTImagePickerAssetsModel]) {
        
        self.dataSource = models
    }
    

    //MARK:actionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            //拍照
            var sourceType = UIImagePickerControllerSourceType.Camera
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
                
                sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            }
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true//设置可编辑
            picker.sourceType = sourceType
            self.presentViewController(picker, animated: true, completion: nil)//进入照相界面
            
        }else if buttonIndex == 2{
            //相册
            let pickerImage = UIImagePickerController()
            if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
                pickerImage.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                pickerImage.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(pickerImage.sourceType)!
            }
            
            pickerImage.delegate = self
            
            pickerImage.allowsEditing = true
            
            self.presentViewController(pickerImage, animated: true, completion: nil)
        }
        
    }
    //MARK:UIImagePickerControllerDelegate
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]){
        
        var img: UIImage!
        
        img = info[UIImagePickerControllerEditedImage] as! UIImage
        self.IMG = img
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        self.upUserHeadimg()
        
    }

    //MARK:RGFadeDelegate
    func sendBtnDown(text: String) {
        if index == 2{
            self.modityDic = ["signature": text]
        }
        if index == 5{
            self.modityDic = ["unitaddress": text]
        }
        if index == 7{
            self.modityDic = ["unitmain": text]
        }
        if index == 50{
            self.modityDic = ["introduction": text]
        }
        self.modifyUserInfo()
    }
    //MARK:UserCompanyTheMainDelegate
    func comple(theMainArr: NSArray) -> Void{
        var unitMain: String = ""
        for index in 0...theMainArr.count - 1{
            
            var unitmainStr: String!
            
            if index == theMainArr.count - 1{
                unitmainStr = theMainArr[index] as! String
                
            }else{
                unitmainStr = (((theMainArr[index] ) as! String) + ",")
            }
            
            unitMain += unitmainStr
            
        }
        self.modityDic = ["unitmain": unitMain]
        self.modifyUserInfo()
        
    }
    //MARK:target
    func signOut(sender: UIButton){
        let alertView = UIAlertView(title: "退出", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
        
        alertView.show()
        
    }
    //MARK:BriefTableViewCellDelegate
    func changeBrief(text: String){
        self.brief = text
        self.modityDic = ["introduction": self.brief!]
        self.modifyUserInfo()
    }
    //MARK:alertDelegate
    func alertView(alertView: UIAlertView,clickedButtonAtIndex buttonIndex: Int){
        if (buttonIndex == 1){
            print("退出")
            DataTool.loginOut({ (newModel) in
                guard newModel != nil else {
                    return
                }
                self.msg = newModel
                SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
                
                NSUserDefaults.standardUserDefaults().setBool(false, forKey: "k_UD_isLogin")
                
                NSUserDefaults.standardUserDefaults().synchronize()
                
            self.navigationController?.popToRootViewControllerAnimated(true)
                
            })

        }
        
    }
    //MARK: 第三方绑定账号和解除
    func wechat(){
        ShareSDK.authorize(SSDKPlatformType.TypeWechat, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
            self.json = "\(user)"
            self.number = user.uid
            self.bindingAccountNumber("weixin")//调第三方绑定
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            self.getUserCompanyInfo()
            case SSDKResponseState.Cancel:  print("操作取消")
            self.getUserCompanyInfo()
            default:
                break
            }
        })

    }
    func tencent(){
        ShareSDK.authorize(SSDKPlatformType.TypeQQ, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
            self.json = "\(user)"
            self.number = user.uid
            self.bindingAccountNumber("qq")//调第三方绑定
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            self.getUserCompanyInfo()
            case SSDKResponseState.Cancel:  print("操作取消")
            self.getUserCompanyInfo()
            default:
                break
            }
        })

    }
    func sina(){
        ShareSDK.authorize(SSDKPlatformType.TypeSinaWeibo, settings: nil, onStateChanged: { (state : SSDKResponseState, user : SSDKUser!, error : NSError!) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("授权成功,用户信息为\(user)\n ----- 授权凭证为\(user.credential)")
            self.json = "\(user)"
            self.number = user.uid
            self.bindingAccountNumber("sina")//调第三方绑定
            case SSDKResponseState.Fail:    print("授权失败,错误描述:\(error)")
            self.getUserCompanyInfo()
            case SSDKResponseState.Cancel:  print("操作取消")
            self.getUserCompanyInfo()
            default:
                break
            }
        })

        
    }
    //MARK:networking
    //我的个人信息
    func getUserCompanyInfo(){
        DataTool.getUserCompany({ (newModel) in
                guard newModel != nil else {
                    return
                }
                self.model = newModel
            })
    }
    
    //上传头像
    func upUserHeadimg(){
        
        DataTool.upload(self.IMG, completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
            
            self.getUserCompanyInfo()
            
        })
    }
    //修改个人信息
    func modifyUserInfo(){
        DataTool.modifyUserInfomation(self.modityDic!, completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
           
            self.getUserCompanyInfo()
            
        })
        
    }
    
    //第三方绑定
    func bindingAccountNumber(type: String){
        let url = String(format: "%@user/binding/\(type)",BaseUrl)
        let paramDic = ["json": self.json!, "number": self.number!]
        
        DataTool.bingdingsThirdNumber(url, param: paramDic, completionHandler:({(newModel) in
            guard newModel != nil else {
                return
            }
            SVProgressHUD.showSuccessWithStatus(newModel?.msg)
            self.getUserCompanyInfo()
            
        }))
    }
    //解绑第三方账号
    func tiedThirdPartyAccount(){
        let url = String(format: "%@user/binding/dodel",BaseUrl)
        let paramDic = ["type": self.bingdingtype!]
        
        DataTool.releaseThirdNumber(url, param: paramDic, completionHandler: ({(newModel) in
            guard newModel != nil else {
                return
            }
            SVProgressHUD.showSuccessWithStatus(newModel?.msg)
            self.getUserCompanyInfo()
            
        }))
        
    }

}
